package com.xuzao.developer.config;

import com.alibaba.fastjson.JSON;
import com.xuzao.developer.base.model.SysPower;
import com.xuzao.developer.base.model.SysResource;
import com.xuzao.developer.dao.SysPowerDao;
import com.xuzao.developer.dao.SysResourceDao;
import com.xuzao.developer.utils.BJUIMap;
import com.xuzao.developer.utils.LoginUserInfoUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author xuzao
 * @description
 * @date 2019-08-22 11:48
 */
@Component
public class SessionFilter implements Filter {


    private String[] includeUrls = new String[]{"/index/login", "/"};
    @Resource
    private SysPowerDao sysPowerDao;
    @Resource
    private SysResourceDao sysResourceDao;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession(true);
        String url = request.getRequestURI();

        System.out.println("filter url:" + url);
        //是否需要过滤
        boolean needFilter = isNeedFilter(url);

        //不需要过滤直接传给下一个过滤器
        if (!needFilter) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else { //需要过滤器
            // session中包含user对象,则是登录状态

            if (session == null || session.getAttribute("user") == null) {
                String requestType = request.getHeader("X-Requested-With");
                //判断是否是ajax请求
                if (requestType != null && "XMLHttpRequest".equals(requestType)) {
                    BJUIMap bjuiMap = new BJUIMap();
                    bjuiMap.setMessage("登录已失效，请重新登录");
                    bjuiMap.setStatusCode(BJUIMap.CODE_ERROR);
                    response.setContentType("text/JavaScript; charset=utf-8");
                    response.getWriter().write(JSON.toJSONString(bjuiMap));
                } else {
                    response.sendRedirect("/");
                }

                return;
            } else {
                SysResource sysResource = new SysResource();
                sysResource.setUrl(url);
                List<SysResource> sysResources = sysResourceDao.selectList(sysResource);
                if (sysResources.isEmpty()) {
                    filterChain.doFilter(request, response);
                    return;
                }
                Long userId = LoginUserInfoUtil.getLoginUser().getId();
                SysPower sysPower = new SysPower();
                sysPower.setUserId(userId);
                sysPower.setUrl(url);
                List<SysPower> sysPowerList = sysPowerDao.selectList(sysPower);
                if (sysPowerList.isEmpty()) {
                    response.setContentType("text/JavaScript; charset=utf-8");
                    BJUIMap bjuiMap = new BJUIMap();
                    bjuiMap.setMessage("无权限");
                    bjuiMap.setStatusCode(BJUIMap.CODE_ERROR);
                    response.getWriter().write(JSON.toJSONString(bjuiMap));
                    return;
                }
                filterChain.doFilter(request, response);

            }
        }
    }

    public boolean isNeedFilter(String uri) {
        if (uri.endsWith(".css") || uri.endsWith(".js") || uri.endsWith(".ico") || uri.endsWith(".jpg") || uri.endsWith(".png")
                || uri.endsWith(".git")) {
            return false;
        }

        for (String includeUrl : includeUrls) {
            if (includeUrl.equals(uri)) {
                return false;
            }
        }

        return true;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

}
